package com.itheima.ws;


import com.itheima.utils.MessageUtils;
import lombok.Data;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;

/**
 * 目前看来websocket的写法也是有模板的。每个会话有对应的session，后续的发消息都是通过这个session。
 * 需要把session统一维护管理
 */
@Data
@Component
@ServerEndpoint(value = "/chat", configurator = GetHttpSessionConfigurator.class)
public class ChatEndpoint {

    private Session session;

    private HttpSession httpSession;

    static HashMap<String, ChatEndpoint> onlineUsers = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig){
        //一个客户端建议一个连接，就对应一个ws的Session，我们把对应的Session统一封装到ChatEndpoint里，用一个在线客户的集合进行管理
        this.session = session;
        HttpSession httpSession = (HttpSession) endpointConfig.getUserProperties().get((HttpSession.class.getName()));
        this.httpSession = httpSession;
        onlineUsers.put((String) httpSession.getAttribute("user"),this);

        //ws建立后，需要广播该用户上线的消息
        Set<String> names = onlineUsers.keySet();
        String message = MessageUtils.getMessage(true, null, names);
        broadcastSystemMessage(message);

    }

    private void broadcastSystemMessage(String message) {
        try {
            Set<String> names = onlineUsers.keySet();
            for (String name : names) {
                ChatEndpoint chatEndpoint = onlineUsers.get(name);
                chatEndpoint.session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {

    }
    @OnError
    public void onError(Session session, Throwable throwable) {

    }
}
